import React, {useEffect, useState, useRef} from 'react'
import {Button, Space, Tag, message} from 'antd'
import {history, connect, useModel} from 'umi'
import moment from 'moment'
import {uploadFileUrl} from '@/service/common/upload'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import BatchUpload from './components/BatchUpload'
import BatchUploadImg from './components/BatchUploadImg'
import {getCompany} from '@/service/system/company'
import {modelSeriesFun, translateDataToTree} from '@/utils/common/index'
import {getXZCarTypeList} from '@/service/carMessage/list'
import Permissions from '@/components/Permissions'
import {downloadDocumentUrl} from '@/service/common/download'
// api调用
import {
	getTableList,
	checkData,
	importAccident,
} from '@/service/carMessage/accident'

import 'moment/locale/zh-cn'
// 字典
import {insuranceType, operationType} from '../dict'
import {getDict} from '@/service/common/dict'
import {getHolderDictInfo} from '@/service/common'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

const renewalDom = (props: {
	user: {orgId: string | number; userName: string; userId: string}
	location: any
}) => {
	// 导入
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [fileObj, setFileObj] = useState<any>()
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [dict, setDict] = useState({
		Claim_Insurance_Type: [],
		Accident_Status: [],
		Accident_Level: [],
		Accident_Type: [],
		Duty_Type: [],
	})

	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [tableList, setTableList] = useState<any[]>([])
	const [formData, setFormData] = useState<any[]>([])
	const [orgSource, setOrgSource] = useState<any>([])
	const [carTypeList, setCarTypeList] = useState<any>([])
	const [otherData, setOtherData] = useState<any>()

	// 批量导入车辆图片
	const [isCarImgModalOpen, setIsCarImgModalOpen] = useState(false)

	const [holderDict, setHolderDict] = useState([])
	/** 获取持有方数据 */
	useEffect(() => {
		getHolderDictInfo({type: 'holder'}).then((res: any) => {
			if (res?.success) {
				setHolderDict(res?.data)
			}
		})
	}, [])
	const batchColumns: any = [
		{
			title: '被保人',
			dataIndex: 'insured',
			align: 'center',
			width: 300,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '报案时间',
			dataIndex: 'reporterTime',
			align: 'center',
			width: 250,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '保单类型',
			dataIndex: 'insuranceType',
			align: 'center',
			width: 250,
			render: (text: number) => (
				<>
					{insuranceType?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '事故状态',
			dataIndex: 'accidentStatus',
			align: 'center',
			width: 150,
			render: (text: string) => (
				<>
					{dict.Accident_Status?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text) {
								return (
									<Tag color="processing">
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '车架号',
			dataIndex: 'vin',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '报案号',
			dataIndex: 'reportNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '发动机号',
			dataIndex: 'engineNumber',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '事故类型',
			dataIndex: 'accidentType',
			align: 'center',
			width: 200,
			render: (text: string) => (
				<>
					{dict.Accident_Type?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text) {
								return (
									<Tag color="processing">
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '报案人',
			dataIndex: 'reporter',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '更新时间',
			dataIndex: 'updateTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '保单号',
			dataIndex: 'insuranceNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '出现地点',
			dataIndex: 'occurrencePlace',
			align: 'center',
			width: 250,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '错误信息',
			dataIndex: 'errorMsg',
			align: 'center',
			width: 200,
			fixed: 'right',
			render: (text: string) => <span>{text || '--'}</span>,
		},
	]
	// 获取表格数据
	const onListFun = () => {
		delete otherData?.insuranceOrder
		delete otherData?.reporterDate
		delete otherData?.occurrence
		delete otherData?.closure
		setLoading(true)
		getTableList({
			...params,
			...otherData,
		})
			.then((res: any) => {
				if (res?.success) {
					setTableList(() => res?.data?.records)
					setTotal(res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}
	const importData = () => {
		const formdata = new FormData()
		formdata.append('excel', fileObj)
		formdata.append('type', '2')
		importAccident(formdata)
			.then((res: any) => {
				if (res?.success) {
					message.success(res.msg)
					setIsModalOpen(() => false)
					onListFun()
				}
			})
			.catch((error: any) => {
				message.error(error)
			})
	}

	// 获取品牌车系
	const onCarTypeListFun = () => {
		getXZCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
	}

	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	useEffect(() => {
		onCarTypeListFun()
		getDict(
			{
				dictKeys: [
					'Claim_Insurance_Type',
					'Accident_Status',
					'Accident_Level',
					'Accident_Type',
					'Duty_Type',
				],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	// 列表
	const columns = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '持有方',
			dataIndex: 'holderName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '所属公司',
			dataIndex: 'orgName',
			align: 'center',
			width: 140,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 150,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '运营分类',
			dataIndex: 'operationType',
			align: 'center',
			width: 150,
			render: (text: number) => (
				<>
					{operationType?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === Number(text)) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '资产所有方',
			dataIndex: 'assertsOwnerName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '保单号',
			dataIndex: 'insuranceNo',
			align: 'center',
			width: 240,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车险类别',
			dataIndex: 'insuranceType',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{insuranceType?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '保单签单日期',
			dataIndex: 'insuranceOrderTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '保险公司',
			dataIndex: 'insuranceCompanyName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '案件状态',
			dataIndex: 'accidentStatus',
			align: 'center',
			width: 200,
			render: (text: string) => (
				<>
					{dict.Accident_Status?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text) {
								return (
									<Tag color="processing">
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '报案号',
			dataIndex: 'reportNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '立案号/赔案号',
			dataIndex: 'compensationNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '报案人',
			dataIndex: 'reporter',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '被保险人',
			dataIndex: 'insured',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车型',
			dataIndex: 'carBrandSeries',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '出险时间',
			dataIndex: 'occurrenceTime',
			align: 'center',
			width: 200,
			render: (text: string) => (
				<span>{moment(text).format('YYYY-MM-DD') || '--'}</span>
			),
		},
		{
			title: '报案日期',
			dataIndex: 'reporterTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '事故类型',
			dataIndex: 'accidentType',
			align: 'center',
			width: 200,
			render: (text: string) => (
				<>
					{dict.Accident_Type?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text) {
								return (
									<Tag color="processing">
										{item?.dictValue}
									</Tag>
								)
							}
							return null
						},
					)}
				</>
			),
		},
		{
			title: '责任划分',
			dataIndex: 'dutyType',
			align: 'center',
			width: 200,
			render: (text: string) => (
				<>
					{dict.Duty_Type?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text) {
								return (
									<Tag color="processing">
										{item?.dictValue}
									</Tag>
								)
							}
							return null
						},
					)}
				</>
			),
		},
		{
			title: '事故等级',
			dataIndex: 'accidentLevelType',
			align: 'center',
			width: 200,
			render: (text: string) => (
				<>
					{dict.Accident_Level?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text) {
								return (
									<Tag color="processing">
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '结案日期',
			dataIndex: 'closureTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '司机姓名',
			dataIndex: 'driverName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '身份证号',
			dataIndex: 'driverCardNo',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '最近更新时间',
			dataIndex: 'updateTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '更新人',
			dataIndex: 'updateUserName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text: string, record: any) => (
				<div>
					<Permissions permissionID="amc_assetCenter_carMessage_accident_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/accident/view',
									query: {
										id: record.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_accident_edit">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/accident/edit',
									query: {
										id: record.id,
									},
								})
							}}>
							编辑
						</Button>
					</Permissions>
				</div>
			),
		},
	]
	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [otherData])
	// 搜索
	const onFinish = (values: any) => {
		const insuranceOrderStart: string =
			values?.insuranceOrder &&
			moment(values?.insuranceOrder[0]).format('YYYY-MM-DD')
		const insuranceOrderEnd: string =
			values?.insuranceOrder &&
			moment(values?.insuranceOrder[1]).format('YYYY-MM-DD')
		const reporterStart: string =
			values?.reporterDate &&
			moment(values?.reporterDate[0]).format('YYYY-MM-DD')
		const reporterEnd: string =
			values?.reporterDate &&
			moment(values?.reporterDate[1]).format('YYYY-MM-DD')
		const occurrenceStart: string =
			values?.occurrence &&
			moment(values?.occurrence[0]).format('YYYY-MM-DD')
		const occurrenceEnd: string =
			values?.occurrence &&
			moment(values?.occurrence[1]).format('YYYY-MM-DD')
		const closureStart: string =
			values?.closure && moment(values?.closure[0]).format('YYYY-MM-DD')
		const closureEnd: string =
			values?.closure && moment(values?.closure[1]).format('YYYY-MM-DD')
		setOtherData(() => ({
			...values,
			insuranceOrderTimeStr: values?.insuranceOrder
				? `${insuranceOrderStart}~${insuranceOrderEnd}`
				: null,
			reporterTimeStr: values?.reporterDate
				? `${reporterStart}~${reporterEnd}`
				: null,
			occurrenceTimeStr: values?.occurrence
				? `${occurrenceStart}~${occurrenceEnd}`
				: null,
			closureTimeStr: values?.closure
				? `${closureStart}~${closureEnd}`
				: null,
		}))
	}

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}

	useEffect(() => {
		onOrgFun()
	}, [props?.user?.orgId])

	// 重置
	const onReset = () => {
		setOtherData({})
	}

	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'select',
						label: '持有方',
						name: 'holderId',
						key: 'holderId',
						keys: 'value',
						title: 'valueName',
						items: [...holderDict],
					},
					{
						type: 'input',
						key: 'carPlateNo',
						name: 'carPlateNo',
						label: '车牌号',
					},
					{
						type: 'select',
						key: 'fashionId',
						name: 'fashionId',
						label: '品牌车系车型',
						keys: 'id',
						title: 'fullName',
						items: [...carTypeList],
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'input',
						key: 'insuranceNo',
						name: 'insuranceNo',
						label: '保单号',
					},
					{
						type: 'select',
						key: 'carStatus',
						name: 'carStatus',
						label: '车险类别',
						keys: 'key',
						title: 'label',
						items: [...insuranceType],
					},
					{
						type: 'dateRange',
						key: 'insuranceOrder',
						name: 'insuranceOrder',
						label: '保险签单日期',
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'select',
						key: 'insuranceCompanyCode',
						name: 'insuranceCompanyCode',
						label: '保险公司',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.Claim_Insurance_Type],
					},
					{
						type: 'select',
						key: 'accidentStatus',
						name: 'accidentStatus',
						label: '案件状态',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.Accident_Status],
					},
					{
						type: 'input',
						key: 'reportNo',
						name: 'reportNo',
						label: '报案号',
					},
				],
			},
			{
				type: 'group',
				key: 'group4',
				groupItems: [
					{
						type: 'input',
						key: 'compensationNo',
						name: 'compensationNo',
						label: '立案号/赔案号',
					},
					{
						type: 'input',
						key: 'reporter',
						name: 'reporter',
						label: '报案人',
					},
					{
						type: 'dateRange',
						key: 'reporterDate',
						name: 'reporterDate',
						label: '报案日期',
					},
				],
			},
			{
				type: 'group',
				key: 'group5',
				groupItems: [
					{
						type: 'input',
						key: 'insured',
						name: 'insured',
						label: '被保险人',
					},
					{
						type: 'dateRange',
						key: 'occurrence',
						name: 'occurrence',
						label: '出险时间',
					},
					{
						type: 'select',
						key: 'accidentLevelType',
						name: 'accidentLevelType',
						label: '事故等级',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.Accident_Level],
					},
				],
			},
			{
				type: 'group',
				key: 'group6',
				groupItems: [
					{
						type: 'select',
						key: 'dutyType',
						name: 'dutyType',
						label: '责任划分',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.Duty_Type],
					},

					{
						type: 'dateRange',
						key: 'closure',
						name: 'closure',
						label: '结案日期',
					},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [orgSource, carTypeList, dict])

	const resetList = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}
	// 批量导入车辆图片取消
	const carImgModalOpen = () => {
		setIsCarImgModalOpen(() => false)
	}

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_assetCenter_carMessage_accident_bactchImport">
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => {
								setIsModalOpen(() => true)
							}}>
							批量上传
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_accident_bactchImportImg">
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => {
								setIsCarImgModalOpen(() => true)
							}}>
							批量上传事故图片
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_accident_bactchExport">
						<Button
							ghost
							size="small"
							className="btn_warning"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '116',
									queryDesc: '事故理赔导出,resourceId:116',
									queryParam: otherData,
								})
							}}>
							批量导出
						</Button>
					</Permissions>
				</Space>
			</div>
			<CustomTable
				kid="id"
				params={params}
				columns={columns}
				scroll={{y: 450}}
				pagination
				total={total}
				callback={(pagination: any) => {
					setParams(pagination)
				}}
				showRowSelection
				selectCallback={() => {}}
				loading={loading}
				dataSource={tableList}
			/>
			<BatchUpload
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
				setFileObj={setFileObj}
				importData={importData}
				fileNmae="excel"
				fileData={{type: 1}}
				kid="id"
				uploadFileUrl={checkData}
				columns={batchColumns}
				sourceId={4}
				templateType="理赔订单字段（汇总）"
			/>
			<BatchUploadImg
				title="批量上传事故图片"
				isModalOpen={isCarImgModalOpen}
				setIsModalOpen={carImgModalOpen}
				accept={['image/jpeg', 'image/png']}
				moreNum={50}
				fileNmae={fileName}
				resetList={resetList}
				fileData={{
					modelName: 'accident',
					targetAttr: 0,
				}}
				uploadFileUrl={uploadFileUrl}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(renewalDom)
